<template>
  <div class="client-ssoAuthServer-edit">
    <!-- 添加或修改授权服务器对话框 -->
    <el-dialog v-model="isShowDialog" width="800px" :close-on-click-modal="false" :destroy-on-close="true">
      <template #header>
        <div v-drag="['.client-ssoAuthServer-edit .el-dialog', '.client-ssoAuthServer-edit .el-dialog__header']">{{(!formData.id || formData.id==0?'添加':'修改')+'授权服务器'}}</div>
      </template>
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="190px">
        <el-form-item label="授权服务名称" prop="serverName">
          <el-select filterable clearable v-model="formData.serverName" placeholder="请选择授权服务名称" >
            <el-option
              v-for="dict in serverNameOptions"
              :key="dict.value"
              :label="dict.label"
                  :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用ID" prop="clientId">
          <el-input v-model="formData.clientId" placeholder="请输入应用ID" />
        </el-form-item>
        <el-form-item label="应用密钥" prop="clientSecret">
          <el-input v-model="formData.clientSecret" placeholder="请输入应用密钥" />
        </el-form-item>
        <el-form-item label="引导认证页地址" prop="authUrl">
          <el-input v-model="formData.authUrl" placeholder="请输入引导认证页地址" />
        </el-form-item>
        <el-form-item label="回调地址" prop="callbackUrl">
          <el-input v-model="formData.callbackUrl" placeholder="请输入回调地址" />
        </el-form-item>
        <el-form-item label="code换取accessToken地址" prop="codeTokenUrl">
          <el-input v-model="formData.codeTokenUrl" placeholder="请输入code换取accessToken地址" />
        </el-form-item>
        <el-form-item label="code换取请求方式" prop="codeTokenType">
          <el-select filterable clearable v-model="formData.codeTokenType" placeholder="请选择code换取请求方式" >
            <el-option
              v-for="dict in codeTokenTypeOptions"
              :key="dict.value"
              :label="dict.label"
                  :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="刷新token地址" prop="refreshTokenUrl">
          <el-input v-model="formData.refreshTokenUrl" placeholder="请输入刷新token地址" />
        </el-form-item>
        <el-form-item label="刷新token请求方式" prop="refreshTokenType">
          <el-select filterable clearable v-model="formData.refreshTokenType" placeholder="请选择刷新token请求方式" >
            <el-option
              v-for="dict in refreshTokenTypeOptions"
              :key="dict.value"
              :label="dict.label"
                  :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用logo" prop="logo">
          <el-upload
            v-loading="upLoadingLogo"
            :action="baseURL+'api/v1/system/upload/singleImg'"
            :before-upload="beforeAvatarUploadLogo"
            :data="setUpData()"
            :on-success="handleAvatarSuccessLogo"
            :show-file-list="false"
            class="avatar-uploader"
            name="file"
          >
            <img v-if="!proxy.isEmpty(imageUrlLogo)" :src="imageUrlLogo" class="avatar">
            <el-icon v-else class="avatar-uploader-icon"><ele-Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="onSubmit" :disabled="loading">确 定</el-button>
          <el-button @click="onCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { reactive, toRefs, ref,unref,getCurrentInstance,computed } from 'vue';
import {ElMessageBox, ElMessage, FormInstance,UploadProps} from 'element-plus';
import {
  listSsoAuthServer,
  getSsoAuthServer,
  delSsoAuthServer,
  addSsoAuthServer,
  updateSsoAuthServer,
} from "/@/api/system/sso/client/ssoAuthServer";
import {getToken} from "/@/utils/gfast"
import {
  SsoAuthServerTableColumns,
  SsoAuthServerInfoData,
  SsoAuthServerTableDataState,
  SsoAuthServerEditState
} from "/@/views/system/sso/client/ssoAuthServer/list/component/model"
defineOptions({ name: "ApiV1SsoClientSsoAuthServerEdit"})
const emit = defineEmits(['ssoAuthServerList'])
  const props = defineProps({
    serverNameOptions:{
      type:Array,
      default:()=>[]
    },
    codeTokenTypeOptions:{
      type:Array,
      default:()=>[]
    },
    refreshTokenTypeOptions:{
      type:Array,
      default:()=>[]
    },
  })
const baseURL:string|undefined|boolean = import.meta.env.VITE_API_URL
const {proxy} = <any>getCurrentInstance()
const formRef = ref<HTMLElement | null>(null);
const menuRef = ref();
//图片上传地址
const imageUrlLogo = ref('')
//上传加载
const upLoadingLogo = ref(false)
const state = reactive<SsoAuthServerEditState>({
  loading:false,
  isShowDialog: false,
  formData: {
    id: undefined,
    serverName: undefined,
    clientId: undefined,
    clientSecret: undefined,
    authUrl: undefined,
    callbackUrl: undefined,
    codeTokenUrl: undefined,
    codeTokenType: undefined,
    refreshTokenUrl: undefined,
    refreshTokenType: undefined,
    createdBy: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    logo: undefined,
    deletedAt: undefined,
  },
  // 表单校验
  rules: {
    serverName : [
        { required: true, message: "授权服务名称不能为空", trigger: "blur" }
    ],
    clientId : [
        { required: true, message: "应用ID不能为空", trigger: "blur" }
    ],
    clientSecret : [
        { required: true, message: "应用密钥不能为空", trigger: "blur" }
    ],
    authUrl : [
        { required: true, message: "引导认证页地址不能为空", trigger: "blur" }
    ],
    callbackUrl : [
        { required: true, message: "回调地址称不能为空", trigger: "blur" }
    ],
    codeTokenUrl : [
        { required: true, message: "code换取accessToken地址不能为空", trigger: "blur" }
    ]
  }
});
const { loading,isShowDialog,formData,rules } = toRefs(state);
// 打开弹窗
const openDialog = (row?: SsoAuthServerInfoData) => {
  resetForm();
  if(row) {
    getSsoAuthServer(row.id!).then((res:any)=>{
      const data = res.data;
      data.serverName = ''+data.serverName
      data.codeTokenType = ''+data.codeTokenType
      data.refreshTokenType = ''+data.refreshTokenType
      //单图地址赋值
      imageUrlLogo.value = data.logo ? proxy.getUpFileUrl(data.logo) : ''
      state.formData = data;
  })
}
  state.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
  state.isShowDialog = false;
};
defineExpose({
  openDialog,
});
// 取消
const onCancel = () => {
  closeDialog();
};
// 提交
const onSubmit = () => {
  const formWrap = unref(formRef) as any;
  if (!formWrap) return;
  formWrap.validate((valid: boolean) => {
    if (valid) {
      state.loading = true;
      if(!state.formData.id || state.formData.id===0){
        //添加
      addSsoAuthServer(state.formData).then(()=>{
          ElMessage.success('添加成功');
          closeDialog(); // 关闭弹窗
          emit('ssoAuthServerList')
        }).finally(()=>{
          state.loading = false;
        })
      }else{
        //修改
      updateSsoAuthServer(state.formData).then(()=>{
          ElMessage.success('修改成功');
          closeDialog(); // 关闭弹窗
          emit('ssoAuthServerList')
        }).finally(()=>{
          state.loading = false;
        })
      }
    }
  });
};
const resetForm = ()=>{
  state.formData = {
    id: undefined,
    serverName: undefined,
    clientId: undefined,
    clientSecret: undefined,
    authUrl: undefined,
    callbackUrl: undefined,
    codeTokenUrl: undefined,
    codeTokenType: undefined,
    refreshTokenUrl: undefined,
    refreshTokenType: undefined,
    createdBy: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    logo: undefined,
    deletedAt: undefined,
  }
  imageUrlLogo.value = ''
};
//单图上传应用logo
const handleAvatarSuccessLogo:UploadProps['onSuccess'] = (res, file) => {
  if (res.code === 0) {
    imageUrlLogo.value = URL.createObjectURL(file.raw!)
    state.formData.logo = res.data.path
  } else {
    ElMessage.error(res.msg)
  }
  upLoadingLogo.value = false
}
const beforeAvatarUploadLogo = () => {
  upLoadingLogo.value = true
  return true
}
const setUpData = () => {
  return { token: getToken() }
}
</script>
<style scoped>
  .client-ssoAuthServer-edit :deep(.avatar-uploader .avatar) {
    width: 178px;
    height: 178px;
    display: block;
  }
  .client-ssoAuthServer-edit :deep(.avatar-uploader .el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  .client-ssoAuthServer-edit :deep(.avatar-uploader .el-upload:hover) {
    border-color: var(--el-color-primary);
  }
  .client-ssoAuthServer-edit :deep(.el-icon.avatar-uploader-icon) {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  .kv-label{margin-bottom: 15px;font-size: 14px;}
  .mini-btn i.el-icon{margin: unset;}
  .kv-row{margin-bottom: 12px;}
</style>
